/*
* FilePremier Chrome Plugin
*/

var autodownload = -1;
var popupPos = "right: 5px";
var autoreconnect = false;
var showpopup = true;
var neverReconnected = true;
var regexpute = new Array(
   /http:\/\/(\w+\.)?megaupload\.com\/([a-zA-Z]+\/)?\?[a-zA-Z]=[0-9a-zA-Z]{8}/g,
    /(http|https):\/\/(\w+\.)?rapidshare\.com\/(files\/[0-9]+\/[0-9a-zA-Z\.-_]+|#!d)[^( |"|>|<|\r\n\|\n|$)]+/g,
    /(http|https):\/\/rs[a-z0-9]+.rapidshare\.com\/(files\/[^( |"|>|<|\r\n\|\n|$)]+|#!download[^( |"|>|<|\r\n\|\n|$)]+)/g,
    /http:\/\/(\w+\.)?megavideo\.com\/([a-zA-Z]+\/)?\?[a-zA-Z]=[0-9a-zA-Z]{8}/g,
    /http:\/\/(\w+\.)?netload\.in\/[0-9a-zA-Z]+\/?(.*)?\.htm/g,
    /http:\/\/(\w+\.)?fileserve\.com\/file\/[^\"\r\n< ]+/g,
    /http:\/\/(\w+\.)?hotfile\.com\/dl\/[0-9a-zA-Z]+\/[\/[0-9a-zA-Z]+\//g,
	 /http:\/\/(www\.)?uploadstation\.com\/file\/[^( |"|>)]+/g,
    /http:\/\/(\w+\.)?(sharingmatrix|filesonic)\.(com|fr|de|it|net|org|jp)\/file\/[^\"\r\n< ]+/g,
    /http:\/\/(\w+\.)?(wupload)\.(com|fr|de|it|net|org|jp)\/file\/[^\"\r\n< ]+/g,
    /http:\/\/(www\.)?fileserve\.com\/list\/[^( |"|>)]+/g,
    /http:\/\/(\w+\.)?(wupload)\.(com|fr|de|it|net|org|jp)\/folder\/[^\"\r\n< ]+/g,
    /http:\/\/(\w+\.)?netfolder\.in\/(folder\.php\?folder_id\=(\w+)|([0-9a-zA-Z]+)\/[0-9]+)/g,
    /http:\/\/(www\.)?hotfile\.com\/list\/[^( |"|>)]+/g,
    /http:\/\/(www\.)?uploadstation\.com\/list\/[^( |"|>)]+/g,
    /http:\/\/(www\.)?filesonic\.(com|it|de|es|fr|hk|jp)\/folder\/[^( |"|>)]+/g,
    /http:\/\/(\w+\.)?uploading\.com\/files\/[0-9A-Za-z]+\/?(.*)?/g,
    /http:\/\/(\w+\.)?linksave\.in\/([0-9a-zA-Z]+)/g
    );

chrome.extension.sendRequest({'action' : 'getPrefs'}, getPrefCallback);

function fileDebridCheckLink(link) {
    if(!link) return 0;
    var i;
    for(i=0;i<regexpute.length;i++) {
            var res = link.match(regexpute[i]);

            if(res) {
                return true;
            }
    }
    return 0;
}

function getPrefCallback(saywhat){
	console.log("getPrefCallback");
    showpopup = fileDebridCheckLink(document.location.href);
    popupPos = saywhat.b;
	var mydiv = document.createElement("div");
    mydiv.id = "filepremier-panel-popup";
    mydiv.setAttribute("style","font: normal normal normal 13px/1.231 arial, helvetica, clean, sans-serif; position: fixed; bottom: 3px; margin: 0px; padding: 10px 10px 10px 10px; overflow: visible; backgroundColor: transparent; z-index: 9999999999999999999999999999;");
    mydiv.innerHTML = '<div class="file-panel-bloc nonhova" onmouseover="this.className= \'file-panel-bloc hova\';" onmouseout="this.className = \'file-panel-bloc nonhova\';"><div id="file-panel-header"><div id="file-panel-logo" width="32" height="32" class="normal"></div><div id="file-panel-title">' + chrome.i18n.getMessage("popup_default_title_text") + '</div></div><br /><div id="file-panel-box" ><div id="file-panel-link">' + chrome.i18n.getMessage("popup_default_link_text") + '</div><div id="file-panel-video" style="display:none;">' + chrome.i18n.getMessage("popup_video_text") + '</div></div></div>';
    mydiv.className = popupPos;
    mydiv.style.display = (showpopup) ? 'block' : 'none';
    document.body.appendChild(mydiv);

    if(document.location.href.match(/http:\/\/(\w+\.)?mega(video|porn)\.com\/([a-zA-Z]+\/)?\?[a-zA-Z]=[0-9a-zA-Z]{8}/)){
        mydiv.style.top = "10px";
        mydiv.style.bottom = "";
    }

    document.getElementById('file-panel-link').onclick = function() {
		var link = document.location.href;
		if( /http:\/\/(www\.)?megaupload\.com(\/[a-z]{2})?\/\?f=[0-9a-zA-Z]+/.test(link) === true ||
		/http:\/\/(www\.)?hotfile\.com\/list\/[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ||
		/http:\/\/(www\.)?fileserve\.com\/list\/[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ||
		/http:\/\/(www\.)?wupload\.com\/folder\/[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ||
		/http:\/\/(www\.)?filesonic\.(com|it|de|es|fr|hk|jp)\/folder\/[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ||
		/http:\/\/(www\.)?netfolder\.in\/folder.php\?folder_id=[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ||
		/http:\/\/(www\.)?uploadstation\.com\/list\/[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ||
						/http:\/\/(www\.)?linksave\.in\/[^( |"|>|<|\r\n\|\n|$)]+/.test(link) === true ) {
		
			var thelinks =[];
			thelinks.push(document.location.href);
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange= function(){
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						console.log(xhr.responseText);
						if((xhr.responseText).match("invalid")){
							document.getElementById('file-panel-logo').className = "info";
							document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_not_connected_text");
							document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_connect_text");
							document.getElementById('file-panel-link').onclick = function() {
								window.open('http://www.filepremier.com/');
								document.getElementById('file-panel-logo').className = "normal";
								document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_default_title_text");
								document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_regen_link_text");
								document.getElementById('file-panel-link').onclick = function() {
									neverReconnected = true;
									chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : document.location.href}, genPremiumCallback);
								};
							};
							popItUp();
						}
						else
							chrome.extension.sendRequest({action:"aboutDebrid",links:thelinks});
						console.log(thelinks[0]);
					}
				}
			};
			xhr.open("GET", "http://www.filepremier.com/fpapi/check.php",true);
			xhr.send("");
			
		}
		else
			chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : document.location.href}, genPremiumCallback);
	};

    autoreconnect = saywhat.d;
    autodownload = saywhat.e;
	
	if(autodownload > -1) {
        window.setTimeout(function() {
            chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : document.location.href}, genPremiumCallback);
         },(autodownload*1000));
    }
}

function getPrefLightCallback(saywhat){
    popupPos = saywhat.b;
    document.getElementById('filepremier-panel-popup').className = popupPos;
    autoreconnect = saywhat.d;
}

document.addEventListener('click', function(e) { 
    var target = (e && e.target) || (event && event.srcElement);
    var obj = document.getElementById('filepremier-panel-popup');
    (target != obj) ? obj.style.display = 'none' : null;
} ,false)

function genPremiumCallback(saywhat)
{
	console.log("getPremiumCallback say:" + saywhat );
			
	document.getElementById('file-panel-video').style.display = 'none';
    isDownloading = false;
    isReconnecting = false;
		
    isSuccess = saywhat.match(/http+[^"><]+/g);
    if(isSuccess) {
		premium_link = saywhat.match(/http+[^"><]+/g);
        if (premium_link){
			if(premium_link[1]) {
					
                document.getElementById('file-panel-logo').className = "normal";
                document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_default_title_text");
                document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_default_link_text");
                document.getElementById('file-panel-link').onclick = function() { document.location.href = premium_link[0]; };
				
                document.getElementById('file-panel-video').innerHTML = chrome.i18n.getMessage("popup_video_text");
                document.getElementById('file-panel-video').style.display = 'block';
                document.getElementById('file-panel-video').onclick = function() { document.location.href = premium_link[1] };
            } else {
                isDownloading = true;
               //document.location.href = premium_link[0];
			   window.open(premium_link[0]);
            }
        }
		localStorage["requestLink"] = "";
    }
    else {
        isError = saywhat.match(/[^"><]+/);
		if(autoreconnect && neverReconnected) {
                chrome.extension.sendRequest({'action' : 'reConnect'}, autoReconnectCallback);
                isReconnecting = true;
        } 
		else{
			if(isError == "ERROR: account_expired") {
					document.getElementById('file-panel-logo').src = "info";
					document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_server_message_text");
					document.getElementById('file-panel-link').innerHTML = "Not Premium";
					document.getElementById('file-panel-link').onclick = function() {
					chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : localStorage["requestLink"]}, genPremiumCallback);
				};
			}
			else if(isError == "ERROR: missing_parameters") {
				document.getElementById('file-panel-logo').className = "info";
                document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_not_connected_text");
                document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_connect_text");
                document.getElementById('file-panel-link').onclick = function() {
                    window.open('http://www.filepremier.com/');
                    document.getElementById('file-panel-logo').className = "normal";
                    document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_default_title_text");
                    document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_regen_link_text");
                    document.getElementById('file-panel-link').onclick = function() {
                        neverReconnected = true;
                        chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : localStorage["requestLink"]}, genPremiumCallback);
                    };
                };
			}
			else {
					document.getElementById('file-panel-logo').className= "error";
					document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_error_link_text");
					document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_regen_link_text");;
					document.getElementById('file-panel-link').onclick = function() {
					chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : localStorage["requestLink"]}, genPremiumCallback);
				};
			}
		}
		
	}
    document.getElementById('filepremier-panel-popup').style.display = (isDownloading || isReconnecting) ? 'none' : 'block';
}

function escapeHTML (str) {
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
};

function popItUp() {
    if(document.getElementById('filepremier-panel-popup').style.display == 'none') {
        chrome.extension.sendRequest({'action' : 'getPrefs'}, getPrefLightCallback);
        document.getElementById('filepremier-panel-popup').style.display = 'block';
        return;
    }
    document.getElementById('filepremier-panel-popup').style.display = 'none';
}

function autoReconnectCallback(saywhat) {
	console.log("autoReconnectCallback");
    neverReconnected = false;
    if(saywhat) {
        chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : document.location.href}, genPremiumCallback);
        return;
    }

    document.getElementById('file-panel-logo').className = "error";
    document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_error_autoco_text");
    document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_error_userpass_text");
    document.getElementById('file-panel-link').onclick = function() {
        window.open('http://www.filepremier.com/premium.php');
        document.getElementById('file-panel-logo').className = "normal";
        document.getElementById('file-panel-title').innerHTML = chrome.i18n.getMessage("popup_default_title_text");
        document.getElementById('file-panel-link').innerHTML = chrome.i18n.getMessage("popup_regen_link_text");
        document.getElementById('file-panel-link').onclick = function() {
            neverReconnected = true;
            chrome.extension.sendRequest({'action' : 'triggerGenPremium', 'url' : document.location.href}, genPremiumCallback);
        };
    };
}
